﻿using UnityEngine;
using System.Collections;

namespace net {
	public class BuyBtns : MonoBehaviour {
		NetLvConfig lvCfg;
		bool isP1 = false;

		void Start(){
			lvCfg = gameObject.transform.root.GetComponent<NetLvConfig>();
		}

		void OnMouseDown() {
			NetLvPkg pkg = lvCfg.findByLv(1);

			string name = transform.name;

			if(GameObject.FindGameObjectWithTag ("TANK_PLAYER_P1").transform.networkView.isMine){
				isP1 = true;
			}

			int p = GameObject.FindGameObjectWithTag ("TANK_PLAYER_P1").transform.networkView.isMine ? 1 : 2;
			string prefabPath = "";

			int[] prices = {
				50, 80, 100, 80
			};

			if (name.StartsWith ("buy1")) {
				print ("buy1");
				if (NetMain.assetCount > prices[0]) {
					// 在T_的位置刷enemy1_ai_p几？
					prefabPath = "prefab/enemy1_ai_p" + p;
					// 扣物资
					NetMain.assetCount -= prices[0];
				}
			} else if (name.StartsWith ("buy2")) {
				print ("buy2");
				if (NetMain.assetCount > prices[1]) {
					// 在T_的位置刷enemy2_ai_p几？
					prefabPath = "prefab/enemy2_ai_p" + p;
					// 扣物资
					NetMain.assetCount -= prices[1];

					pkg = lvCfg.findByLv(2);
				}

			} else if (name.StartsWith ("buy3")) {
				print ("buy3");
				if (NetMain.assetCount > prices[2]) {
					// 在T_的位置刷enemy3_ai_p几？
					prefabPath = "prefab/enemy3_ai_p" + p;
					// 扣物资
					NetMain.assetCount -= prices[2];

					pkg = lvCfg.findByLv(3);
				}
			} else if (name.StartsWith ("buy4")) {
				print ("buy4");
				if (NetMain.assetCount > prices[3]) {
					// 在T_的位置刷enemy1_ai_p几？
					prefabPath = "prefab/enemy4_ai_p" + p;
					// 扣物资
					NetMain.assetCount -= prices[3];

					pkg = lvCfg.findByLv(4);
				}
			}

			if(prefabPath.Equals("")){
				return ;
			}

			Object newAIobj =Network.Instantiate(Resources.Load(prefabPath), Buy.T_pos, Quaternion.identity,0);
			GameObject newAI = (GameObject)newAIobj;
print("pkg.armor="+pkg.armor+"pkg.level="+pkg.level);
			newAI.GetComponent<NetAI>().armor = pkg.armor;
			newAI.GetComponent<NetAI>().level = pkg.level;
			networkView.RPC("callAIState",RPCMode.All,pkg.armor,pkg.level,isP1,newAI.networkView.viewID);
		}

		[RPC]
		public void callAIState(int armor,int level,bool isP1,NetworkViewID id){
			GameObject tank = NetworkView.Find(id).gameObject;
			if(!tank.networkView.isMine){
				tank.GetComponent<NetAI>().armor = armor;
				tank.GetComponent<NetAI>().level = level;

			}
		}
	}
}